#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by ZhangYichao on 2018/12/03

import requests
import json
import urllib
from bs4 import BeautifulSoup

class GoogleTranslateAPI(object):
    @staticmethod
    def getHTMLText(url):
        try:
            r = requests.get(url, timeout=30)
            r.raise_for_status()
            return r.text
        except:
            print("Get HTML Text Failed!")
            return 0


    @staticmethod
    def google_translate_EtoC(to_translate, from_language="en", to_language="zh-CN"):
        # 根据参数生产提交的网址
        base_url = "https://translate.google.cn/m?hl={}&sl={}&ie=UTF-8&q={}"
        url = base_url.format(to_language, from_language, to_translate)

        # 获取网页
        html = GoogleTranslateAPI.getHTMLText(url)
        if html:
            soup = BeautifulSoup(html, "html.parser")

        # 解析网页得到翻译结果
        try:
            result = soup.find_all("div", {"class": "t0"})[0].text
        except:
            print("Translation Failed!")
            result = ""

        return result

    @staticmethod
    def google_translate_CtoE(to_translate, from_language="zh-CN", to_language="en"):
        # 根据参数生产提交的网址
        base_url = "https://translate.google.cn/m?hl={}&sl={}&ie=UTF-8&q={}"
        url = base_url.format(to_language, from_language, to_translate)

        # 获取网页
        html = GoogleTranslateAPI.getHTMLText(url)
        if html:
            soup = BeautifulSoup(html, "html.parser")

        # 解析网页得到翻译结果
        try:
            result = soup.find_all("div", {"class": "t0"})[0].text
        except:
            print("Translation Failed!")
            result = ""

        return result
